package com.personal.utils.excel.service;

import com.alibaba.fastjson.JSONObject;
import com.personal.utils.excel.utils.ImportRecordUtils;
import com.personal.utils.excel.utils.PoiUtils;
import com.personal.utils.excel.utils.WriteExcelFileUtil;
import com.personal.utils.excel.utils.bean.CellFormatBean;
import com.personal.utils.excel.utils.bean.SheetDataBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * description: ExcelFileService <br>
 * date: 2020/4/20 16:57 <br>
 * author: wenjun.dai <br>
 * version: 1.0 <br>
 */
@Service
@Slf4j
public class ExcelFileService {

    private String dataImportColumns = "phone,contactName,company,product,sex,birthday,createTime,industry,mail," +
            "tel,province,city,postcode,address,wechat,qq,remark,type,level,points,regTime,status" ;

    /**
     * 文件读写操作示例:
     * 获取Excel文件中指定索引的sheet页并做校验,写出错误数据
     *
     * @param fileEncode
     * @param fileName
     */
    public File sheetDataBeanByIndex(String fileEncode, String fileName, int index) {
        //1.读取表中数据;
        File file = PoiUtils.getFile(fileEncode, fileName);
        List<String> insteadColumnList = Arrays.asList(dataImportColumns.split(","));

        // 根据索引,获取单个 sheet 文件内容
        SheetDataBean sheetDataBean = PoiUtils.getSheetDataBean(file, index, insteadColumnList);
        List<Map<String, String>> fileDataList = sheetDataBean.getSheetDataList();

        List<CellFormatBean> cellFormatBeanList = new ArrayList<>();
        List<Map<String, String>> errorDataList = new ArrayList();
        //2.组装cdp所需格式数据
        for (Map<String, String> map : fileDataList) {
            //数据处理校验
            ImportRecordUtils.validData(map, errorDataList, cellFormatBeanList);
        }
        // 4.错误数据处理
        if (!errorDataList.isEmpty()) {
            sheetDataBean.setCellFormatBeanList(cellFormatBeanList);
            sheetDataBean.setSheetDataList(errorDataList);
            log.info("有问题的数据: {} ", JSONObject.toJSONString(errorDataList));
            //错误数据文件生成
            //错误数据文件生成
            File errorDataFile = WriteExcelFileUtil.writeFileDefaultBySheet(sheetDataBean, fileName);
            return errorDataFile;
        }
        return null;
    }


}
